<template>
  <div class="color">
    <el-tag
      v-for="tag in dynamicTags"
      :key="tag.value"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag.label }}
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model="inputValue"
      class="w-20"
      size="small"
      placeholder="请输入颜色"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button v-else class="button-new-tag" size="small" @click="showInput"> + 新增 </el-button>
  </div>
</template>

<script setup>
import { pageColorList } from '@renderer/views/option.js'
import { useUserStore } from '@renderer/stores/user'
const userStore = useUserStore()
import { useUserDB } from '@renderer/database/useUserDB'
const { addPageColor, getCurrentUser, removeFromArrayField } = useUserDB()

const InputRef = ref(null)
const inputVisible = ref(false)
const dynamicTags = ref([])
const inputValue = ref('')

onMounted(() => {
  dynamicTags.value = [...userStore.pageColorList]
})
const handleClose = async (tag) => {
  dynamicTags.value.splice(tag.value, 1)
  let user = await getCurrentUser()
  removeFromArrayField(user.userName, 'pageColorList', (color) => color.value === tag.value)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value.input.focus()
  })
}

const handleInputConfirm = async () => {
  if (inputValue.value) {
    dynamicTags.value.push({
      value: dynamicTags.value.length - 1,
      label: inputValue.value
    })
    userStore.pageColorList = [...dynamicTags.value]

    let user = await getCurrentUser()
    addPageColor(user.userName, userStore.pageColorList)
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>

<style lang="scss" scoped>
.color {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  .w-20 {
    width: 120px;
  }
}
</style>
